package com.etlmaster.executor.boot;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.etlmaster.core.DataSourceDefine;
import com.etlmaster.core.DataSourceHolder;
import com.etlmaster.executor.parser.XmlJobDbLoader;
import com.etlmaster.executor.utils.DpExecutorUtils;
import com.etlmaster.executor.utils.LogWriter;

import freemarker.core.FreeMarkerTemplate;

/**
 * 将流程信息导出成xml
 * 
 * @author Wugf
 * @date 2016-03-08
 */
public class ExportJobToXml {
	public static void export(XmlJobDbLoader loader){
		Map<String,Object> jobInfos=new HashMap<String,Object>();
		jobInfos.putAll(loader.jobParam);
		jobInfos.put("steps", loader.rowList);
		jobInfos.put("dbs", getDataSourceList());
		String jobXml=FreeMarkerTemplate.getFpls("proc", jobInfos);
		String logPath = DpExecutorUtils.getLogPath()+"/"+DpExecutorUtils.DateFormater(new Date(),"yyyyMMdd");
		try {
			DpExecutorUtils.writeToFile(jobXml, "xml", logPath,loader.jobParam.get("job_id").toString());
		} catch (IOException e) {
			LogWriter.addLog("ERROR","生成流程信息错误！！{}",e.getMessage());
		}
	}
	private static List<Map<String,String>> getDataSourceList(){
		Map<String,DataSourceDefine> dsMap=DataSourceHolder.getInstance().getDsDefs();
		Iterator it=dsMap.keySet().iterator();
		List<Map<String,String>> dsList=new ArrayList<Map<String,String>>();
		while(it.hasNext()){
			Map<String,String> dsEntry=new HashMap<String,String>();
			DataSourceDefine def=(DataSourceDefine) dsMap.get(it.next());
			dsEntry.put("dbname", def.getId());
			dsEntry.put("cnname", def.getName());
			dsEntry.put("driverclassname", def.getDriverClassName());
			dsEntry.put("url", def.getUrl());
			dsEntry.put("username", def.getUsername());
			dsEntry.put("password", def.getPassword());
			dsEntry.put("jndiname", def.getJndiName());
			if(def.getAlias()!=null&&def.getAlias().length>0)
				dsEntry.put("alias", def.getAlias()[0]);
			else
				dsEntry.put("alias", "");
			dsList.add(dsEntry);
		}
		return dsList;
	}

}
